<template>
  <div class="database-monitor">
    <div class="monitor-toolbar">
      <div class="time-tabs">
        <span class="time-tab" :class="{'active': timeRange === '1h'}" @click="changeTimeRange('1h')">近1小时</span>
        <span class="time-tab" :class="{'active': timeRange === '6h'}" @click="changeTimeRange('6h')">近3小时</span>
        <span class="time-tab" :class="{'active': timeRange === '1d'}" @click="changeTimeRange('1d')">近24小时</span>
        <span class="time-tab" :class="{'active': timeRange === '7d'}" @click="changeTimeRange('7d')">近7天</span>
      </div>
      <el-button icon="el-icon-refresh" size="small" @click="fetchData">自定义刷新</el-button>
    </div>

    <div class="monitor-grid">
      <!-- CPU使用率 -->
      <div class="chart-card">
        <div class="chart-header">
          <div class="metric-info">
            <div class="metric-name">CPU使用率(%)</div>
            <div class="tooltip-icon"><i class="el-icon-info"></i></div>
          </div>
          <div class="chart-values">
            <span class="value-label">最大值/平均值</span>
            <span class="max-value">7.51</span>
            <span class="avg-value">3.12</span>
          </div>
        </div>
        <div class="chart-container" id="cpuChart"></div>
      </div>

      <!-- 内存使用率 -->
      <div class="chart-card">
        <div class="chart-header">
          <div class="metric-info">
            <div class="metric-name">内存使用率(%)</div>
            <div class="tooltip-icon"><i class="el-icon-info"></i></div>
          </div>
          <div class="chart-values">
            <span class="value-label">最大值/平均值</span>
            <span class="max-value">19.40</span>
            <span class="avg-value">19.30</span>
          </div>
        </div>
        <div class="chart-container" id="memoryChart"></div>
      </div>

      <!-- IOPS -->
      <div class="chart-card">
        <div class="chart-header">
          <div class="metric-info">
            <div class="metric-name">IOPS</div>
            <div class="tooltip-icon"><i class="el-icon-info"></i></div>
          </div>
          <div class="chart-values">
            <span class="value-label">最大值/平均值</span>
            <span class="max-value">12.15</span>
            <span class="avg-value">6.35</span>
          </div>
        </div>
        <div class="chart-container" id="iopsChart"></div>
      </div>

      <!-- 网络输入吞吐量 -->
      <div class="chart-card">
        <div class="chart-header">
          <div class="metric-info">
            <div class="metric-name">网络输入吞吐量</div>
            <div class="select-unit">
              <el-select v-model="networkInUnit" size="mini">
                <el-option label="KB/s" value="KB/s"></el-option>
              </el-select>
            </div>
          </div>
          <div class="chart-values">
            <span class="value-label">最大值/平均值</span>
            <span class="max-value">8.56</span>
            <span class="avg-value">1.50</span>
          </div>
        </div>
        <div class="chart-container" id="networkInChart"></div>
      </div>

      <!-- 网络输出吞吐量 -->
      <div class="chart-card">
        <div class="chart-header">
          <div class="metric-info">
            <div class="metric-name">网络输出吞吐量</div>
            <div class="select-unit">
              <el-select v-model="networkOutUnit" size="mini">
                <el-option label="KB/s" value="KB/s"></el-option>
              </el-select>
            </div>
          </div>
          <div class="chart-values">
            <span class="value-label">最大值/平均值</span>
            <span class="max-value">18.66</span>
            <span class="avg-value">1.65</span>
          </div>
        </div>
        <div class="chart-container" id="networkOutChart"></div>
      </div>

      <!-- 数据库连接数 -->
      <div class="chart-card">
        <div class="chart-header">
          <div class="metric-info">
            <div class="metric-name">数据库连接数</div>
            <div class="tooltip-icon"><i class="el-icon-info"></i></div>
          </div>
          <div class="chart-values">
            <span class="value-label">最大值/平均值</span>
            <span class="max-value">33</span>
            <span class="avg-value">30</span>
          </div>
        </div>
        <div class="chart-container" id="connectionChart"></div>
      </div>

      <!-- 当前活跃连接数 -->
      <div class="chart-card">
        <div class="chart-header">
          <div class="metric-info">
            <div class="metric-name">当前活跃连接数</div>
            <div class="tooltip-icon"><i class="el-icon-info"></i></div>
          </div>
          <div class="chart-values">
            <span class="value-label">最大值/平均值</span>
            <span class="max-value">1</span>
            <span class="avg-value">1</span>
          </div>
        </div>
        <div class="chart-container" id="activeConnectionChart"></div>
      </div>

      <!-- QPS -->
      <div class="chart-card">
        <div class="chart-header">
          <div class="metric-info">
            <div class="metric-name">QPS</div>
            <div class="tooltip-icon"><i class="el-icon-info"></i></div>
          </div>
          <div class="chart-values">
            <span class="value-label">最大值/平均值</span>
            <span class="max-value">14.73</span>
            <span class="avg-value">3.60</span>
          </div>
        </div>
        <div class="chart-container" id="qpsChart"></div>
      </div>

      <!-- TPS -->
      <div class="chart-card">
        <div class="chart-header">
          <div class="metric-info">
            <div class="metric-name">TPS</div>
            <div class="tooltip-icon"><i class="el-icon-info"></i></div>
          </div>
          <div class="chart-values">
            <span class="value-label">最大值/平均值</span>
            <span class="max-value">0.23</span>
            <span class="avg-value">0</span>
          </div>
        </div>
        <div class="chart-container" id="tpsChart"></div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import {showMetricDatamore} from "@/api/resell/orderinstancesql";

export default {
  name: 'DatabaseMonitor',
  props: {
    currentResource: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      timeRange: '1h',
      networkInUnit: 'KB/s',
      networkOutUnit: 'KB/s',
      charts: {},
      metricsData: {
        cpu: { times: [], values: [], max: 0, avg: 0 },
        memory: { times: [], values: [], max: 0, avg: 0 },
        iops: { times: [], values: [], max: 0, avg: 0 },
        networkIn: { times: [], values: [], max: 0, avg: 0 },
        networkOut: { times: [], values: [], max: 0, avg: 0 },
        connections: { times: [], values: [], max: 0, avg: 0 },
        activeConnections: { times: [], values: [], max: 0, avg: 0 },
        qps: { times: [], values: [], max: 0, avg: 0 },
        tps: { times: [], values: [], max: 0, avg: 0 }
      },
      chartsInitialized: false
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts();
      this.fetchData();
    });
  },
  methods: {
    changeTimeRange(range) {
      this.timeRange = range;
      this.fetchData();
    },
    
    initCharts() {
      // 初始化所有图表
      const chartConfigs = [
        { id: 'cpuChart', name: 'cpu', color: '#409EFF', formatter: '{b}<br/>CPU使用率: {c}%' },
        { id: 'memoryChart', name: 'memory', color: '#19BE6B', formatter: '{b}<br/>内存使用率: {c}%' },
        { id: 'iopsChart', name: 'iops', color: '#67C23A', formatter: '{b}<br/>IOPS: {c}次/秒' },
        { id: 'networkInChart', name: 'networkIn', color: '#E6A23C', formatter: '{b}<br/>网络输入: {c} KB/s' },
        { id: 'networkOutChart', name: 'networkOut', color: '#F56C6C', formatter: '{b}<br/>网络输出: {c} KB/s' },
        { id: 'connectionChart', name: 'connections', color: '#909399', formatter: '{b}<br/>连接数量: {c}' },
        { id: 'activeConnectionChart', name: 'activeConnections', color: '#9B55FF', formatter: '{b}<br/>活跃连接: {c}' },
        { id: 'qpsChart', name: 'qps', color: '#FF9F00', formatter: '{b}<br/>QPS: {c}次/秒' },
        { id: 'tpsChart', name: 'tps', color: '#00BFFF', formatter: '{b}<br/>TPS: {c}次/秒' }
      ];
      
      chartConfigs.forEach(config => {
        const element = document.getElementById(config.id);
        if (element) {
          this.charts[config.name] = echarts.init(element);
          this.charts[config.name].setOption({
            tooltip: {
              trigger: 'axis',
              formatter: config.formatter,
              axisPointer: {
                type: 'cross',
                label: {
                  backgroundColor: '#6a7985'
                }
              }
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              top: '5%',
              containLabel: true
            },
            xAxis: {
              type: 'category',
              boundaryGap: false,
              data: [],
              axisLine: { lineStyle: { color: '#EBEEF5' } },
              axisLabel: { color: '#606266', fontSize: 10 }
            },
            yAxis: {
              type: 'value',
              axisLine: { show: false },
              axisTick: { show: false },
              splitLine: { lineStyle: { color: '#EBEEF5', type: 'dashed' } },
              axisLabel: { color: '#606266', fontSize: 10 }
            },
            series: [{
              name: config.name,
              type: 'line',
              smooth: true,
              symbol: 'none',
              lineStyle: { width: 2, color: config.color },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: `${config.color}30` },
                  { offset: 1, color: `${config.color}10` }
                ])
              },
              data: []
            }]
          });
        }
      });
      
      // 添加窗口大小变化的监听器
      window.addEventListener('resize', this.resizeCharts);
      this.chartsInitialized = true;
    },
    
    resizeCharts() {
      for (const key in this.charts) {
        if (this.charts[key]) {
          this.charts[key].resize();
        }
      }
    },
    
    fetchData() {
      this.currentResource.other1 = 1;
      showMetricDatamore(this.currentResource).then(response => {
        if (response.code === 200 && response.rows) {
          this.processMonitorData(response.rows);
        }
      }).catch(error => {
        console.error("获取监控数据失败:", error);
      });
    },
    
    processMonitorData(rows) {
      // 重置数据
      Object.keys(this.metricsData).forEach(key => {
        this.metricsData[key] = { times: [], values: [], max: 0, avg: 0 };
      });
      
      // 处理每种指标数据
      rows.forEach(item => {
        const datapoints = item.datapoints || [];
        if (!datapoints.length) return;
        
        // 提取时间数据(只需提取一次)
        if (this.metricsData.cpu.times.length === 0) {
          this.metricsData.cpu.times = datapoints.map(point => {
            const date = new Date(parseInt(point.timestamp));
            return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
          });
          
          // 所有图表使用相同的时间轴
          Object.keys(this.metricsData).forEach(key => {
            if (key !== 'cpu') {
              this.metricsData[key].times = [...this.metricsData.cpu.times];
            }
          });
        }
        
        // 根据指标类型提取值
        const values = datapoints.map(point => parseFloat(point.average || 0));
        const max = Math.max(...values);
        const avg = values.reduce((sum, val) => sum + val, 0) / values.length;
        
        switch (item.metric_name) {
          case 'rds001_cpu_util':
            this.metricsData.cpu.values = values;
            this.metricsData.cpu.max = max.toFixed(2);
            this.metricsData.cpu.avg = avg.toFixed(2);
            break;
          case 'rds002_mem_util':
            this.metricsData.memory.values = values;
            this.metricsData.memory.max = max.toFixed(2);
            this.metricsData.memory.avg = avg.toFixed(2);
            break;
          case 'rds003_iops':
            this.metricsData.iops.values = values;
            this.metricsData.iops.max = max.toFixed(2);
            this.metricsData.iops.avg = avg.toFixed(2);
            break;
          case 'rds004_bytes_in':
            // 转换为KB/s
            this.metricsData.networkIn.values = values.map(v => (v / 1024).toFixed(2));
            this.metricsData.networkIn.max = (max / 1024).toFixed(2);
            this.metricsData.networkIn.avg = (avg / 1024).toFixed(2);
            break;
          case 'rds005_bytes_out':
            // 转换为KB/s
            this.metricsData.networkOut.values = values.map(v => (v / 1024).toFixed(2));
            this.metricsData.networkOut.max = (max / 1024).toFixed(2);
            this.metricsData.networkOut.avg = (avg / 1024).toFixed(2);
            break;
          case 'rds006_conn_count':
            this.metricsData.connections.values = values;
            this.metricsData.connections.max = Math.round(max);
            this.metricsData.connections.avg = Math.round(avg);
            break;
          case 'rds007_conn_active_count':
            this.metricsData.activeConnections.values = values;
            this.metricsData.activeConnections.max = Math.round(max);
            this.metricsData.activeConnections.avg = Math.round(avg);
            break;
          case 'rds008_qps':
            this.metricsData.qps.values = values;
            this.metricsData.qps.max = max.toFixed(2);
            this.metricsData.qps.avg = avg.toFixed(2);
            break;
          case 'rds009_tps':
            this.metricsData.tps.values = values;
            this.metricsData.tps.max = max.toFixed(2);
            this.metricsData.tps.avg = avg.toFixed(2);
            break;
        }
      });
      
      this.updateCharts();
    },
    
    updateCharts() {
      // 更新所有图表数据
      const chartUpdates = [
        { chart: 'cpu', data: this.metricsData.cpu },
        { chart: 'memory', data: this.metricsData.memory },
        { chart: 'iops', data: this.metricsData.iops },
        { chart: 'networkIn', data: this.metricsData.networkIn },
        { chart: 'networkOut', data: this.metricsData.networkOut },
        { chart: 'connections', data: this.metricsData.connections },
        { chart: 'activeConnections', data: this.metricsData.activeConnections },
        { chart: 'qps', data: this.metricsData.qps },
        { chart: 'tps', data: this.metricsData.tps }
      ];
      
      chartUpdates.forEach(update => {
        if (this.charts[update.chart]) {
          this.charts[update.chart].setOption({
            xAxis: { data: update.data.times },
            series: [{ data: update.data.values }]
          });
        }
      });
    }
  },
  beforeDestroy() {
    // 移除事件监听
    window.removeEventListener('resize', this.resizeCharts);
    
    // 销毁图表实例
    for (const key in this.charts) {
      if (this.charts[key]) {
        this.charts[key].dispose();
        this.charts[key] = null;
      }
    }
  }
}
</script>

<style scoped>
.database-monitor {
  padding: 0px;
}

.monitor-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 8px 16px;
  background-color: #fff;
  border-radius: 4px;
}

.time-tabs {
  display: flex;
  align-items: center;
}

.time-tab {
  padding: 6px 12px;
  margin-right: 16px;
  font-size: 13px;
  color: #606266;
  cursor: pointer;
  border-radius: 4px;
}

.time-tab.active {
  color: #409EFF;
  font-weight: 500;
  background-color: #ecf5ff;
}

.monitor-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.chart-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  padding: 16px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.metric-info {
  display: flex;
  align-items: center;
}

.metric-name {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.tooltip-icon {
  margin-left: 8px;
  color: #909399;
  cursor: pointer;
}

.select-unit {
  margin-left: 8px;
}

.chart-values {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.value-label {
  color: #909399;
  margin-right: 8px;
}

.max-value {
  color: #303133;
  margin-right: 8px;
}

.avg-value {
  color: #606266;
}

.chart-container {
  height: 200px;
  width: 100%;
}

/* 响应式调整 */
@media (max-width: 1400px) {
  .monitor-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .monitor-grid {
    grid-template-columns: 1fr;
  }
}
</style>
